package com.lottery.im.module.chat.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.Api;
import com.lottery.im.module.chat.ui.NewFragmentActivity;
import com.lottery.im.module.tim.message.Message;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.lottery.im.util.transformations.CropCircleTransformation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天界面adapter
 */
public class ChatAdapter extends ArrayAdapter<Message> {

  private int resourceId;
  private View view;
  private ViewHolder viewHolder;

  private Context mContext;

  // 对方的头像，单聊的时候 使用
  private String mFaceUrl = "";

  private OnResendClickListener mOnResendClickListener;

  private String mSelfGroupCardName = "";

  private Message.OnHongBaoClickListener mOnHongBaoClickListener;
  private Message.OnImageClickListener mOnImageClickListener;

  @Override
  public boolean hasStableIds() {
    return true;
  }

  @Override
  public long getItemId(int position) {
    return view != null ? view.getId() : position;
  }

  /**
   * Constructor
   *
   * @param context The current context.
   * @param resource The resource ID for a layout file containing a TextView to use when
   * instantiating views.
   * @param objects The objects to represent in the ListView.
   */
  public ChatAdapter(Context context, int resource, List<Message> objects) {
    super(context, resource, objects);
    resourceId = resource;
    mContext = context;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView != null) {
      view = convertView;
      viewHolder = (ViewHolder) view.getTag();
    } else {
      view = LayoutInflater.from(getContext()).inflate(resourceId, null);
      viewHolder = new ViewHolder();
      viewHolder.leftMessage = view.findViewById(R.id.leftMessage);
      viewHolder.rightMessage = view.findViewById(R.id.rightMessage);
      viewHolder.leftPanel = view.findViewById(R.id.leftPanel);
      viewHolder.rightPanel = view.findViewById(R.id.rightPanel);
      viewHolder.sending = view.findViewById(R.id.sending);
      viewHolder.error = view.findViewById(R.id.sendError);
      viewHolder.sender = view.findViewById(R.id.sender);
      viewHolder.rightDesc = view.findViewById(R.id.rightDesc);
      viewHolder.systemMessage = view.findViewById(R.id.systemMessage);
      viewHolder.leftAvatar = view.findViewById(R.id.leftAvatar);
      viewHolder.rightAvatar = view.findViewById(R.id.rightAvatar);
      view.setTag(viewHolder);
    }

    if (position < getCount()) {
      final Message data = getItem(position);
      data.setSelfGroupCardName(mSelfGroupCardName);
      data.showMessage(viewHolder, getContext());
      setAvatar(data);
      viewHolder.error.setOnClickListener(v -> {
        if (null != mOnResendClickListener) {
          mOnResendClickListener.OnResendClick(position);
        }
      });
      data.setOnHongBaoClickListener((id ,note) -> {
        if (null != mOnHongBaoClickListener) mOnHongBaoClickListener.OnHongBaoClick(id,note);
      });

      data.setOnImageClickListener(url -> {
        if (null != mOnImageClickListener) mOnImageClickListener.OnImageClick(url);
      });
    }

    return view;
  }

  /**
   * 头像显示
   */
  private void setAvatar(Message data) {
    if (data.isSelf()) {
      viewHolder.rightAvatar.setOnClickListener(
          v -> NewFragmentActivity.createSelfProfile(getContext()));
      // 显示自己的头像
      Glide.with(mContext)
          .load(Api.BASEADDRESS + MyApplication.getInstance().getUserInfo().getUserPic())
          .apply(new RequestOptions()
              .bitmapTransform(new CropCircleTransformation())
              .placeholder(R.drawable.icon_conversation_de)
              .error(R.drawable.icon_conversation_de))
          .into(viewHolder.rightAvatar);
    } else {
      viewHolder.leftAvatar.setOnClickListener(
          v -> NewFragmentActivity.create(getContext(), NewFragmentActivity.FragmentInfoType.Other,
              data.getSender()));
      //  显示对方的头像
      TIMConversationType type = data.getMessage().getConversation().getType();
      switch (type) {
        case C2C:
          // 单聊
          if (!TextUtils.isEmpty(mFaceUrl)) {
            Glide.with(mContext)
                .load(mFaceUrl)
                .apply(new RequestOptions()
                    .bitmapTransform(new CropCircleTransformation())
                    .placeholder(R.drawable.icon_conversation_de)
                    .error(R.drawable.icon_conversation_de))
                .into(viewHolder.leftAvatar);
          } else {
            String senderId = data.getMessage().getSender();
            FriendProfile profile = FriendshipInfo.getInstance().getProfile(senderId);
            if (null != profile) {
              // 是好友
              Glide.with(mContext)
                  .load(profile.getAvatarUrl())
                  .apply(new RequestOptions()
                      .bitmapTransform(new CropCircleTransformation())
                      .placeholder(R.drawable.icon_conversation_de)
                      .error(R.drawable.icon_conversation_de))
                  .into(viewHolder.leftAvatar);
            } else {
              //  非好友
              List<String> ids = new ArrayList<>();
              ids.add(senderId);
              TIMFriendshipManager.getInstance().getUsersProfile(ids,
                  new TIMValueCallBack<List<TIMUserProfile>>() {
                    @Override public void onError(int i, String s) {
                    }

                    @Override public void onSuccess(List<TIMUserProfile> timUserProfiles) {
                      if (null != timUserProfiles && timUserProfiles.size() > 0) {
                        mFaceUrl = timUserProfiles.get(0).getFaceUrl();
                        notifyDataSetChanged();
                      }
                    }
                  });
            }
          }

          break;
        case Group:
          // 群聊
          if (null != data.getMessage().getSenderProfile() && !TextUtils.isEmpty(
              data.getMessage().getSenderProfile().getFaceUrl())) {
            Glide.with(mContext)
                .load(data.getMessage().getSenderProfile().getFaceUrl())
                .apply(new RequestOptions()
                    .bitmapTransform(new CropCircleTransformation())
                    .placeholder(R.drawable.icon_conversation_de)
                    .error(R.drawable.icon_conversation_de))
                .into(viewHolder.leftAvatar);
          } else {
            Glide.with(mContext)
                .load(R.drawable.icon_conversation_de)
                .apply(new RequestOptions()
                    .bitmapTransform(new CropCircleTransformation())
                    .placeholder(R.drawable.icon_conversation_de)
                    .error(R.drawable.icon_conversation_de))
                .into(viewHolder.leftAvatar);
          }

          break;
      }
    }
  }

  public class ViewHolder {
    public RelativeLayout leftMessage;
    public RelativeLayout rightMessage;
    public RelativeLayout leftPanel;
    public RelativeLayout rightPanel;
    public ProgressBar sending;
    public ImageView error;
    public ImageView leftAvatar;
    public ImageView rightAvatar;
    public TextView sender;
    public TextView systemMessage;
    public TextView rightDesc;
  }

  public OnResendClickListener getOnResendClickListener() {
    return mOnResendClickListener;
  }

  public void setOnResendClickListener(
      OnResendClickListener onResendClickListener) {
    mOnResendClickListener = onResendClickListener;
  }

  public interface OnResendClickListener {
    void OnResendClick(int postion);
  }

  public void setSelfGroupCardName(String selfGroupCardName) {
    mSelfGroupCardName = selfGroupCardName;
    notifyDataSetChanged();
  }

  public void setOnHongBaoClickListener(
      Message.OnHongBaoClickListener onHongBaoClickListener) {
    mOnHongBaoClickListener = onHongBaoClickListener;
  }

  public void setOnImageClickListener(
      Message.OnImageClickListener onImageClickListener) {
    mOnImageClickListener = onImageClickListener;
  }
}
